package org.linloong.modules.apis.ai.controller;


import cn.dev33.satoken.stp.StpUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.linloong.core.result.Result;
import org.linloong.modules.apis.ai.dto.ConversationVo;
import org.linloong.modules.apis.ai.entity.ChatHistory;
import org.linloong.modules.apis.ai.service.ChatHistoryService;
import org.linloong.modules.apis.ai.service.CurrentChatHistoryService;
import org.springframework.util.Assert;
import org.springframework.web.bind.annotation.*;

import java.util.Arrays;
import java.util.List;
import java.util.Map;

/**
 * @author dbo
 */
@Slf4j
@RestController
@RequestMapping("/api/chatHistory")
@RequiredArgsConstructor
@Tag(name = "聊天历史接口", description = "聊天历史接口")
public class ChatHistoryController {

    private final ChatHistoryService chatHistoryService;

    private final CurrentChatHistoryService currentChatHistoryService;

    @PostMapping(value = "/save")
    @Operation(summary = "保存对话内容", description = "保存对话内容")
    public Result save(@RequestBody ConversationVo conversationVo) {
        return currentChatHistoryService.save(conversationVo);
    }

    @Operation(summary = "获取历史会话列表")
    @GetMapping(value = "/list")
    public Result<List<ChatHistory>> list(String userId, String keyword) {
        LambdaQueryWrapper<ChatHistory> queryWrapper = new LambdaQueryWrapper<>();
        if (StringUtils.isEmpty(userId)){
            userId = StpUtil.getLoginId().toString();
        }
        queryWrapper.eq(ChatHistory::getUserId, userId);
        if (org.apache.commons.lang3.StringUtils.isNotBlank(keyword)){
            queryWrapper.like(ChatHistory::getContent, keyword);
        }
        queryWrapper.orderByDesc(ChatHistory::getTimestamp);
        return Result.success(chatHistoryService.list(queryWrapper));
    }

    @Operation(summary = "获取历史会话列表（分页）")
    @GetMapping(value = "/page")
    public Result<Page<ChatHistory>> page(Page page, String userId, String keyword) {
        LambdaQueryWrapper<ChatHistory> queryWrapper = new LambdaQueryWrapper<>();
        if (StringUtils.isEmpty(userId)){
            userId = StpUtil.getLoginId().toString();
        }
        queryWrapper.eq(ChatHistory::getUserId, userId);
        if (StringUtils.isNotBlank(keyword)){
            queryWrapper.like(ChatHistory::getContent, keyword);
        }
        queryWrapper.orderByDesc(ChatHistory::getTimestamp);
        return Result.success(chatHistoryService.page(page, queryWrapper));
    }

    @Operation(summary = "通过历史记录进入历史对话中")
    @GetMapping(value = "/initChat")
    public Result<Map<String, Object>> initChat(String sessionId) {
        Assert.notNull(sessionId, "会话ID不能为空！");
        return Result.success(currentChatHistoryService.initChat(sessionId));
    }

    @Operation(summary = "删除历史会话", description = "根据ids删除历史会话，多个id用英文都好分隔")
    @DeleteMapping(value = "/delete")
    public Result delete(@RequestParam(required = true) String ids) {
        Assert.notNull(ids, "ids不能为空！");
        chatHistoryService.removeBatchByIds(Arrays.asList(ids.split(",")));
        return Result.success();
    }
}
